<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="ExamPwdForm">
          <a-row>
						<a-col :span="24">
							<a-form-item label="题库" v-bind="validateInfos.bankId" id="ExamPwdForm-bankId" name="bankId">
                <a-select
                 placeholder="请选择题库"
                  ref="select"
                  v-model:value="formData.bankId"
                >
                  <a-select-option v-for='item in res.seldata' :value="item.value">{{ item.label }}</a-select-option>
                  <!-- <a-select-option :value="2">否</a-select-option> -->
                </a-select>
								<!-- <j-dict-select-tag v-model:value="formData.bankId" dictCode="" placeholder="请选择题库ID"  allow-clear /> -->
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="到期时间" v-bind="validateInfos.maturityTime" id="ExamPwdForm-maturityTime" name="maturityTime">
								<a-date-picker placeholder="请选择到期时间"  v-model:value="formData.maturityTime" showTime value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"  allow-clear />
							</a-form-item>
						</a-col>
            <!-- <a-col :span="24" v-if="status != 1">
							<a-form-item label="开始时间" v-bind="validateInfos.startTime" id="ExamPwdForm-maturityTime" name="startTime">
								<a-date-picker placeholder="请选择开始时间"  v-model:value="formData.startTime" showTime value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"  allow-clear />
							</a-form-item>
						</a-col>
            <a-col :span="24" v-if="status != 1">
							<a-form-item label="结束时间" v-bind="validateInfos.stopTime" id="ExamPwdForm-maturityTime" name="stopTime">
								<a-date-picker placeholder="请选择结束时间"  v-model:value="formData.stopTime" showTime value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"  allow-clear />
							</a-form-item>
						</a-col> -->
            <a-col :span="24">
							<a-form-item label="首次考试开始时间"  id="ExamPwdForm-maturityTime" name="">
								<a-date-picker placeholder="请选择开始时间"  v-model:value="formData.startTime" showTime value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"  allow-clear />
							</a-form-item>
						</a-col>
            <a-col :span="24">
							<a-form-item label="第一次考试登录结束时间"  id="ExamPwdForm-maturityTime" name="">
								<a-date-picker placeholder="请选择结束时间"  v-model:value="formData.stopTime" showTime value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"  allow-clear />
							</a-form-item>
						</a-col>
            <a-col :span="24" v-if="status == 1">
							<a-form-item label="二次考试开始时间"  id="ExamPwdForm-maturityTime" name="">
								<a-date-picker placeholder="请选择开始时间"  v-model:value="formData.startTimeTwo" showTime value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"  allow-clear />
							</a-form-item>
						</a-col>
            <a-col :span="24" v-if="status == 1">
							<a-form-item label="第二次考试登录结束时间"  id="ExamPwdForm-maturityTime" name="">
								<a-date-picker placeholder="请选择结束时间"  v-model:value="formData.stopTimeTwo" showTime value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"  allow-clear />
							</a-form-item>
						</a-col>

            <a-col :span="24">
							<a-form-item label="考试时长" v-bind="validateInfos.time" id="ExamPwdForm-maturityTime" name="time">
                <a-input v-model:value="formData.time" placeholder="请输入考试时长(分钟)"   allow-clear >
                </a-input>
								<!-- <a-date-picker placeholder="请输入时长(分钟)"  v-model:value="formData.time" showTime value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"  allow-clear /> -->
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="六位数口令码(唯一标识)" v-bind="validateInfos.passcode" id="ExamPwdForm-passcode" name="passcode">
								<a-input v-model:value="formData.passcode" placeholder="请输入六位数口令码 (唯一标识)"  style="width: 87%;" allow-clear >
                </a-input>
                <a-button @click='getpwds'>获取</a-button>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="考试次数（1，2）" v-bind="validateInfos.passcount" id="ExamPwdForm-passcount" name="passcount">
								<a-input-number v-model:value="formData.passcount" placeholder="请输入考试次数（1，2）" style="width: 100%" />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="是否开启第二次考试" v-bind="validateInfos.isStart" id="ExamPwdForm-isStart" name="isStart">
                <a-select
                 placeholder="请选择是否开启第二次考试"
                  ref="select"
                  v-model:value="formData.isStart"
                  @change="handleChange"
                >
                  <a-select-option :value="1">是</a-select-option>
                  <a-select-option :value="0">否</a-select-option>
                </a-select>
								<!-- <j-dict-select-tag v-model:value="formData.isStart" dictCode="" placeholder="请选择是否开启第二次考试"  allow-clear /> -->
							</a-form-item>
						</a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate,listtiku,getpwd } from '../ExamPwd.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({})},
    formBpm: { type: Boolean, default: true }
  });
  
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    bankId: undefined,
    maturityTime: '',   
    startTime:'',
    stopTime:'',
    time:'',
    startTimeTwo:'',
    stopTimeTwo:'',
    passcode: '',   
    passcount: undefined,
    isStart: undefined,
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = reactive({
    bankId: [{ required: true, message: '请输入题库ID!'},],
    maturityTime: [{ required: true, message: '请输入到期时间!'},],
    // startTime:[{ required: true, message: '请输入开始时间!'},],
    // stopTime:[{ required: true, message: '请输入结束时间!'},],
    time:[{ required: true, message: '请输入时长!'},],
    passcode: [{ required: true, message: '请输入六位数口令码 (唯一标识)!'},],
    passcount: [{ required: true, message: '请输入口令使用次数（1，2）!'},],
    isStart: [{ required: true, message: '请输入是否开启第二次考试!'},],
  });
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

  let status = ref(null)
  const handleChange = (e) =>{
    console.log(e)
    status.value = e
    if(e == 1){
      formData.passcount = 2
    }
  }
  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });

  
  /**
   * 新增
   */
  function add() {
    edit({});
  }
  let kaosTime = reactive({
    twoStartTime:'',
    twoEndTime:'',
  })

  /**
   * 编辑
   */
  function edit(record) {
    console.log(record,"record")
    nextTick(() => {
      status.value = record.isStart == 1 ? 1 : 0;
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
      //赋值
      Object.assign(formData, tmpData);
            // 使用 Object.assign 来触发响应式更新
      //   Object.assign(kaosTime, {
      //   twoStartTime: record.startTimeTwo || '',
      //   twoEndTime: record.stopTimeTwo || ''
      // });
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    try {
      // 触发表单验证
      await validate();
    } catch ({ errorFields }) {
      if (errorFields) {
        const firstField = errorFields[0];
        if (firstField) {
          formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(errorFields);
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    console.log(model,"modelmodelmodelmodel")
    let models = {
      bankId: model.bankId,
      id:model.id,
      isStart:model.isStart,
      maturityTime:model.maturityTime,
      passcode:model.passcode,
      passcount:model.passcount,
      time:model.time,
      timeList:JSON.stringify([{
        startTime:formData.startTime,
        stopTime:formData.stopTime,
      },{
        startTime:formData.startTimeTwo,
        stopTime:formData.stopTimeTwo,
      }]),
    }
    console.log(status.value,"status.value")
    await saveOrUpdate(status.value == 1 ? models : model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          // kaosTime = {
          //   oneStartTime:'',
          //   oneEndTime:'',
          //   twoStartTime:'',
          //   twoEndTime:'',
          // }
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }
  const res = reactive({
    seldata:[]
  })
  const getpwds = async() =>{
    const res = await getpwd('')
    formData.passcode = res
  }
  onMounted(async() => {
    res.seldata = []
    const ress = await listtiku('?column=createTime&order=desc&pageNo=1&pageSize=10')
    console.log(ress.records,"listtiku")
    if(ress.records.length > 0){
      ress.records.forEach((item:any,index:any)=>{
        res.seldata.push({
          label:item.name,
          value:item.id
        })
      })
    }
  })

  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
</style>
